package com.wjk.kylin.rpc.core.netty.client;

import com.wjk.kylin.rpc.core.invoker.RpcConsumerFactory;
import com.wjk.kylin.rpc.core.netty.params.AbstractMessage;
import com.wjk.kylin.rpc.core.serialize.Serializer;
import com.wjk.kylin.rpc.core.util.IpUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * netty pooled client
 * @author wjk
 */
public class NettyConnectClient {
    protected static transient Logger LOGGER = LoggerFactory.getLogger(NettyConnectClient.class);

    private static volatile NioEventLoopGroup group;
    private Channel channel;


    /**
     * 初始化 netty 客户端
     *
     * @param address
     * @param serializer
     * @param consumerFactory
     * @throws Exception
     */
    public void init(String address, Serializer.Algorithm serializer, RpcConsumerFactory consumerFactory) throws Exception {
        // address
        Object[] array = IpUtil.parseIpPort(address);
        String host = (String) array[0];
        int port = (int) array[1];

        // group
        if (group == null) {
            synchronized (NettyConnectClient.class) {
                if (group == null) {
                    group = new NioEventLoopGroup();

                    //结束回调
                    consumerFactory.addStopCallBack(() -> group.shutdownGracefully());
                }
            }
        }

        // init
        final NettyConnectClient thisClient = this;
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new NettyClientChannelInitializer(consumerFactory, thisClient, serializer))
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
        this.channel = bootstrap.connect(host, port).sync().channel();

        // valid
        if (!isValidate()) {
            close();
            return;
        }

        LOGGER.debug(">>>>>>>>>>> kylin-rpc netty client proxy, connect to server success at host:{}, port:{}", host, port);
    }


    public boolean isValidate() {
        if (this.channel != null) {
            return this.channel.isActive();
        }
        return false;
    }

    public void close() {
        if (this.channel != null && this.channel.isActive()) {
            this.channel.close();        // if this.channel.isOpen()
        }
        LOGGER.debug(">>>>>>>>>>> kylin-rpc netty client close.");
    }

    /**
     * 发送消息
     * @param message
     * @throws Exception
     */
    public void send(AbstractMessage message) throws Exception {
        this.channel.writeAndFlush(message).sync();
    }
}
